package cn.wj.school.cloud.security.context;

import org.springframework.util.Assert;

/**
 * 
 * <strong>Title : InheritableThreadLocalContextHolderStrategy.java<br></strong>
 * <strong>Package : cn.b.sky.admin.security.context<br></strong>
 * <strong>Description : </strong>子线程共享<br> 
 * <strong>Create on :  2019-01-19 上午10:34:50<br></strong>
 * <p>
 * @author lidapeng<br>
 * @version <strong>v1.0.0</strong><br>
 * <br>
 * <strong>修改历史:</strong><br>
 * 修改人|修改日期|修改描述<br>
 * -------------------------------------------<br>
 * <br>
 * <br>
 */
public class InheritableThreadLocalContextHolderStrategy implements SecurityContextHolderStrategy {

  //~ Static fields/initializers =====================================================================================

  private static final ThreadLocal<SecurityContext> contextHolder = new InheritableThreadLocal<SecurityContext>();

  //~ Methods ========================================================================================================

  @Override
  public void clearContext() {
      contextHolder.remove();
  }

  @Override
  public SecurityContext getContext() {
      SecurityContext ctx = contextHolder.get();

      if (ctx == null) {
          ctx = createEmptyContext();
          contextHolder.set(ctx);
      }

      return ctx;
  }

  @Override
  public void setContext(SecurityContext context) {
      Assert.notNull(context, "Only non-null SecurityContext instances are permitted");
      contextHolder.set(context);
  }

  @Override
  public SecurityContext createEmptyContext() {
    return new SecurityContextImpl();
  }

}
